<?php

declare(strict_types=1);

namespace App\Controller;


use App\Model\User;
use App\Request\UserRequest;
use Hyperf\HttpServer\Contract\RequestInterface;
use HyperfExt\Jwt\Contracts\JwtFactoryInterface;
use Psr\Http\Message\ResponseInterface;


class AuthController
{

    /**
     *
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function login(RequestInterface $request)
    {
        $credentials = $request->inputs(['name', 'password']);

        if (!$token = auth('api')->attempt($credentials)) {
            return response()->error(msg: '账号或密码错误');
        }

        return $this->respondWithToken($token);
    }

    /**
     * @param $token
     * @return ResponseInterface
     */
    protected function respondWithToken($token): ResponseInterface
    {
        return response()->success([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expire_in' => make(JwtFactoryInterface::class)->make()->getPayloadFactory()->getTtl()
        ]);
    }

    public function me(): ResponseInterface
    {
        return response()->success(auth('api')->user());
    }

    public function refresh(): ResponseInterface
    {
        return response()->success(auth('api')->refresh());
    }

    public function logout(): ResponseInterface
    {
        auth('api')->logout();

        return response()->success(msg: '退出成功');
    }

    public function register(UserRequest $request): ResponseInterface
    {
        $user = User::query()->create($request->all());

        return response()->success($user);
    }
}
